//
//  userAcount.swift
//  weibo_yaoye
//
//  Created by mac on 15/5/16.
//  Copyright (c) 2015年 mac. All rights reserved.
//

import UIKit
import Alamofire

class userAcount: NSObject,Printable,NSCoding {
//    func encodeWithCoder(aCoder: NSCoder)
//    init(coder aDecoder: NSCoder) // NS_DESIGNATED_INITIALIZER

    //--------------step <  42  保存用户的令牌提供下次使用  >--------nextsteplocation<<#currentfile#>>---
    // 令牌
    let access_token: String
    // 令牌有效期
    let expires_in: NSTimeInterval
    // 用户的id
    let uid: String
    // 过期时间
    let expirDate: NSDate
     //--------------step <  50 增加头像和用户名的信息  >--------nextsteplocation<<#currentfile#>>---
    var name: String?
    //头像
    var avatar_large: String? //currentStep: 50
    
    init (dict: [String: AnyObject]) //currentStep: 42
    {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        expirDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
     //--------------step <  45归档路径  >--------nextsteplocation<<#currentfile#>>---
     static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("acount.plist")
    
     //--------------step <  41   使用code  获取token>--------nextsteplocation<<#currentfile#>>---
     //--------------step <  49 通过闭包让控制器掌握令牌的获取成功与否   >--------nextsteplocation<<#currentfile#>>---
    class func loadAccessToken(parames: [String: String],completion:(account: userAcount?, error: NSError?)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        Alamofire.request(.POST, urlString, parameters: parames).responseJSON(){ (_, _, JSON, error) in
          println(JSON)
          println(error)
          if error != nil || JSON == nil
            {
            completion(account: nil, error: error) //currentStep: 49
                return
            }
        
        
         let account = userAcount(dict: JSON! as! [String: AnyObject])  //currentStep: 42
          //--------------step <  51 获取用户名和头像  >--------nextsteplocation<<#currentfile#>>---
          account.loaduserInfo(completion)
         //--------------step <  46  归档  >--------nextsteplocation<<#currentfile#>>---
//          NSKeyedArchiver.archiveRootObject(account, toFile: userAcount.accountPath)
          println("\(NSHomeDirectory())")
          //回调
//          completion(account: account, error: nil)  //currentStep: 49
            }.responseString() {(_, _,JSONString, _) in
                
        }//currentStep: 42
        
    }
    func loaduserInfo(completion:(account: userAcount?,error: NSError?)->()) //currentStep: 51
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["access_token": access_token, "uid": uid]
        Alamofire.request(.GET, urlString, parameters: params).responseJSON { (_, _, JSON, error) in
            if error != nil || JSON == nil
            {
                completion(account: nil, error: error)
                return
            }
            
            if let dict = JSON as? [String: AnyObject]
            {
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
            }
            println(self)
             //--------------step < 52 在这一步归档比较合适  >--------nextsteplocation<NEW>---
             NSKeyedArchiver.archiveRootObject(self, toFile: userAcount.accountPath)
             completion(account: self, error: nil)
            
            
    }
}
     //--------------step <  43 用户数据信息  >--------nextsteplocation<<#currentfile#>>---
    override var description: String {
        let propeities = ["access_token", "uid" , "expires_in" , "expirDate", "name", "avatar_large"]

        return "\(dictionaryWithValuesForKeys(propeities))"
        
    }
    
     //--------------step <  47 解档  >--------nextsteplocation<app代理>---
    class func loadUserAccount() -> userAcount?{
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAcount.accountPath) as? userAcount{
            if account.expirDate.compare(NSDate()) ==  NSComparisonResult.OrderedDescending
            {
                return account
            }
            
        }
        return nil
    }
    

    //MARK - 归档 解档
     //--------------step <  44 归档解档的实现  >--------nextsteplocation<<#currentfile#>>---
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(expirDate, forKey: "expirDate")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")

    }
    
  required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expirDate = aDecoder.decodeObjectForKey("expirDate") as!NSDate
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }
    
}
